<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>canvas绘制和拖动</title>
  </head>
  <body>
    <input type="color" id="color" />
    <canvas id="canvas" style="border: 1px solid #000"></canvas>
    <script>
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");
      const color = document.getElementById("color");
      const dpr = window.devicePixelRatio;
      const shapes = [];
      const initCanvas = () => {
        canvas.width = 800 * dpr;
        canvas.height = 600 * dpr;
      };
      initCanvas();
      class Rect {
        constructor(startX, startY, color) {
          this.startX = startX;
          this.startY = startY;
          this.color = color;
          this.endX = startX;
          this.endY = startY;
        }

        get minX() {
          return Math.min(this.startX, this.endX);
        }
        get minY() {
          return Math.min(this.startY, this.endY);
        }
        get maxX() {
          return Math.max(this.startX, this.endX);
        }
        get maxY() {
          return Math.max(this.startY, this.endY);
        }
        draw() {
          ctx.fillStyle = this.color;
          ctx.fillRect(
            this.minX * dpr,
            this.minY * dpr,
            (this.maxX - this.minX) * dpr,
            (this.maxY - this.minY) * dpr
          );
        }
        change(newX, newY) {
          this.endX = newX;
          this.endY = newY;
        }
      }
      canvas.addEventListener("mousedown", (e) => {
        const mouseX = e.offsetX;
        const mouseY = e.offsetY;
        const shape = new Rect(mouseX, mouseY, color.value);
        shapes.push(shape);
        draw();
        window.addEventListener("mousemove", (e) => {
          const ex = e.clientX - shape.left;
          const ey = e.clientY - shape.top;
          shape.change(ex, ey);
        });
      });
      const draw = () => {
        requestAnimationFrame(draw);
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        shapes.forEach((shape) => {
          shape.draw();
        });
      };
    </script>
  </body>
</html>
